package cn.xiaopengstack.domain.trade.service.lock;

import cn.xiaopengstack.domain.trade.rule.factory.TradeRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.aggregate.LockOrderAggregate;
import cn.xiaopengstack.domain.trade.model.entity.*;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.domain.trade.service.ITradeLockOrderService;
import cn.xiaopengstack.types.framework.strategy.link.mutilModel.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class TradeLockOrderServiceImpl implements ITradeLockOrderService {

    private final ITradeRepository repository;

    private final BusinessLinkedList<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleResponseEntity> tradeRuleValidateFilter;

    public TradeLockOrderServiceImpl(ITradeRepository repository, BusinessLinkedList<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleResponseEntity> tradeRuleValidateFilter) {
        this.repository = repository;
        this.tradeRuleValidateFilter = tradeRuleValidateFilter;
    }

    @Override
    public Optional<MarketOrderEntity> queryUnPayMarketPayOrder(String userId, String outTradeNo) {
        log.info("交易领域，查询拼团订单,userId={}, outOrderId={}", userId, outTradeNo);
        return repository.queryUnPayMarketPayOrder(userId, outTradeNo);
    }

    @Override
    public Optional<ProgressEntity> queryGoodsGroupByProgress(String teamId) {
        log.info("交易领域，查询拼团进度,teamId={}", teamId);
        return repository.queryGoodsGroupByProgress(teamId);
    }

    @Override
    public MarketOrderEntity lockGroupBuyMarketOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {

        TradeRuleResponseEntity applyResult = tradeRuleValidateFilter.apply(TradeRuleCommandEntity
                        .builder()
                        .activityId(payActivityEntity.getActivityId())
                        .userId(userEntity.getUserId())
                        .goodsId(payDiscountEntity.getGoodsId())
                        .teamId(payActivityEntity.getTeamId())
                        .build(),
                new TradeRuleFilterFactory.DynamicContext());


        LockOrderAggregate aggregate = LockOrderAggregate.builder()
                .payDiscountEntity(payDiscountEntity)
                .userEntity(userEntity)
                .payActivityEntity(payActivityEntity)
                .userTakeOverActivityCount(applyResult.getUserTakeOverActivityCount())
                .build();
        return repository.lockGroupBuyMarketOrder(aggregate);
    }

}
